import { Toast } from "antd-mobile"
import { reqcartadd, reqgetgoodsinfo } from "../../http/api"

// state 
const initState = {
    good:{}
}

// action type
const TYPES = {
    DETAIL_GOOD:"DETAIL_GOOD"
}

// reducer
const reducer = (state=initState,action) =>{
    switch(action.type){
        case TYPES.DETAIL_GOOD:
            return {
                ...state,
                good:action.good
            }
        default:
            return state
    }
}

// action creator
export const actions={
    changeGood:good=>({type:TYPES.DETAIL_GOOD,good}),
    reqGood:(id)=>(dispatch,getState)=>{
        let good = getGood(getState());
        if(good.length>0){
            return
        }
        reqgetgoodsinfo({id}).then(res=>{
            if(res.data.code===200){
                dispatch(actions.changeGood(res.data.list[0]))
            }
        })
    },
    addShop:()=>(dispatch,getState)=>{
        let uid = getUid(getState())
        let goodsid = getGoodsId(getState())
        reqcartadd({uid,goodsid,type:1,num:1}).then(res=>{
            if(res.data.code===200){
                Toast.show({
                    content:res.data.msg
                })
            }
        })
    }
}

// selector导出数据给组件
export const getGood = state=>state.detail.good
const getUid = state => state.login.info.uid
const getGoodsId = state => state.detail.good.id
// 导出reducer
export default reducer